import store from '@/store'
import { createRouter, createWebHashHistory } from 'vue-router'
import { Toast } from 'vant'

const routes = [
  {
    path: '/',
    name: '/',
    //重定向
    redirect: "/main/menu"
  },
  //四个板块的页面路由
  {
    path: '/main',
    name: 'main',
    component: () => import('../views/Main.vue'),
    children: [
      {
        path: "menu",
        name: "menu",
        component: () => import('../views/Menu.vue'),
        meta: { index: 1 }
      },
      {
        path: "order",
        name: "order",
        component: () => import('../views/Order.vue'),
        meta: { index: 2, hasLogin: true }//判断是否登陆
      },
      {
        path: "category",
        name: "category",
        component: () => import('../views/Category.vue'),
        meta: { index: 3 }
      },
      {
        path: "user",
        name: "user",
        component: () => import('../views/User.vue'),
        meta: { index: 4 },

      }
    ]
  },
  // 搜索商品
  {
    path: '/searchFood',
    name: 'SearchFood',
    component: () => import('../views/SearchFood.vue'),
    meta: { index: 5 }
  },
  // 商品详情
  {
    path: '/foodDetail',
    name: 'FoodDetail',
    component: () => import('../views/FoodDetail.vue'),
    meta: { index: 6 }
  },
  // 登陆
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { index: 7 }
  },
  // 注册
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { index: 8 }
  },
  //购物车路由
  {
    path: '/shopCart',
    name: 'ShopCart',
    component: () => import('../views/ShopCart.vue'),
    meta: { index: 9, hasLogin: true }
  },
  //添加地址路由
  {
    path: '/AddressInfo',
    name: 'AddressInfo',
    component: () => import('../views/AddressInfo.vue'),
    meta: { index: 10, hasLogin: true }
  },
  //修改地址路由
  {
    path: '/EditAddressInfo',
    name: 'EditAddressInfo',
    component: () => import('../views/EditAddressInfo.vue'),
    meta: { index: 10, hasLogin: true }
  },
  {
    path: "/UserInfo",
    name: "UserInfo",
    component: () => import('../views/UserInfo.vue'),
    meta: { index: 11 },
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 全局前置路由守卫（在每一次路由更改都会触发）
router.beforeEach((to, from) => {
  //判断是否登陆
  if (to.meta.hasLogin === true) {
    if (!store.state.userInfo) {
      Toast("请登录");
      //fullPath拿到所有参数(重定向)
      return to.path = { path: '/login', query: { redirect: to.fullPath } }
    }
  };
  if (to.path === '/main/user') {
    //判断是否登陆
    if (!store.state.userInfo) {
      Toast("请登录");
      //fullPath拿到所有参数(重定向)
      return to.path = { path: '/login', query: { redirect: to.fullPath } }
    }
  }
}
)


export default router
